import { appId, host } from '@/config/h5';
import request from '@/utils/common/request/index';
import { wxjsdkInit } from '@/utils/h5/wxjsdk/index.js';
import wx from 'weixin-js-sdk';

/**
 * @description 公众号授权登录
 */
export const H5Login = function(backRoute) {
	let backUrl = backRoute;
	if (!backUrl) {
		backUrl = encodeURIComponent(getCurrentRoute().fullPath);
	}
	const toUrl = '/pages/login-h5/login-h5';
	const callbackUrl = encodeURIComponent(`${host}/terminal/#${toUrl}?redirect=${backUrl}`);
	window.location.replace(
		`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${callbackUrl}&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect`
	);
};

export const getCurrentRoute = function() {
	let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
	const currentPage = routes[routes.length - 1]; //获取当前页面路由
	return currentPage.$page;
};

/** 
 * @description 获取url上的参数
 */
export const getUrlParam = (name) => {
	let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
	let r = window.location.search.substr(1).match(reg); //匹配目标参数
	if (r != null) return decodeURIComponent(r[2]);
	return null; //返回参数值
}

/**
 * @description 微信原生支付
 */
export const wechatyPay = function(info, callback) {
	function onBridgeReady() {
		WeixinJSBridge.invoke(
			'getBrandWCPayRequest', {
				"appId": info.appId, //公众号ID，由商户传入     
				"timeStamp": info.timestamp, //时间戳，自1970年以来的秒数     
				"nonceStr": info.nonceStr, //随机串     
				"package": info.package,
				"signType": info.signType, //微信签名方式：     
				"paySign": info.paySign //微信签名 
			},
			function(res) {
				callback(res)
			});
	}
	if (typeof WeixinJSBridge == "undefined") {
		if (document.addEventListener) {
			document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
		} else if (document.attachEvent) {
			document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
			document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
		}
	} else {
		onBridgeReady();
	}
};

export const loadImg = (path) => {
	return new Promise((resolve, reject) => {
		let img = new Image();
		img.setAttribute('crossOrigin', 'anonymous');
		img.src = path + '?v=' + Math.random();
		img.onload = function(res) {
			resolve(img);
		}
	});
};


export function h5DebugMode() {
	var script = document.createElement('script');
	script.type = "text/javascript";
	if (script.readyState) { // 如果有这个属性就是IE浏览器
		// 这个函数只有IE浏览器才有，当JS文件被下载完成后就会被触发
		script.onreadystatechange = function() {
			// 当条件满足 表示JS文件以及被下载完成 可以被调用了
			if (script.readyState == 'complete' || script.readyState == 'loaded') {
				new VConsole()
			}
		}
	} else { // 其他主流浏览器
		script.onload = function() { // 浏览下载完成js后 执行onload回调，此时就可以访问JS文件的函数和变量了
			new VConsole()
		}
	}
	script.src = 'https://unpkg.com/vconsole@3.14.7/dist/vconsole.min.js'; // 这一句执行完成，系统就会去下载这个地址里的东西，并且也是异步的去下载
	document.head.appendChild(script); // 当吧script插入
}

export function setShareCard(title, desc, link, imgUrl) {
	return new Promise((resolve, reject) => {
		request({
			url: '/api/reqwxsdk',
			method: 'POST',
			data: {
				url: window.location.href.split('#')[0],
			}
		}).then(config => {
			wxjsdkInit(config, 'updateAppMessageShareData').then(() => {
				updateAppMessageShareData();
			}).catch(error => {
				reject(error)
			})
			wxjsdkInit(config, 'updateTimelineShareData').then(() => {
				updateTimelineShareData();
			}).catch(error => {
				reject(error)
			})
		})

		const updateAppMessageShareData = () => {
			wx.updateAppMessageShareData({
				title, // 分享标题
				desc, // 分享描述
				link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
				imgUrl, // 分享图标
				success: function() {
					resolve()
				},
				fail(err) {
					reject(err)
				}
			})
		}
		const updateTimelineShareData = () => {
			wx.updateTimelineShareData({
				title, // 分享标题
				link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
				imgUrl, // 分享图标
				success: function() {
					resolve()
				},
				fail(err) {
					reject(err)
				}
			})
		}
	})
}